class Image < ActiveRecord::Base
  has_many :comments
  has_and_belongs_to_many :tags

  validates_presence_of :name
  validates_presence_of :path

  def self.find_recent(off, nb, orient)
    self.find(:all, :offset => off, :limit => nb, :order => "created_at DESC", :conditions =>{:orientation => orient})
  end

  def self.save_upload!(upload)
    name =  upload.original_filename
    directory = "#{RAILS_ROOT}/data"
    # create the file path
    path = File.join(directory, name)
    # write the file
    File.open(path, "wb") { |f| f.write(upload.read) }
    path
  end

  def before_destroy
    directory = "#{RAILS_ROOT}/data"
    Dir.foreach(directory) { |f|
      ff = File.join(directory, f)
      File.delete(ff) if f.start_with?(File.basename(path))
    }
  end

  def to_param
    "#{permalink}"
  end

end
